<template>
  <div class="app-container">
    <span style="font-size: medium;color: rgba(151,170,195) "> / 采购计划 / 计划维护</span>

    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px" style="margin-top: 20px">
      <el-form-item label="货品名称" prop="rawProductName">
        <el-input
            v-model="queryParams.rawProductName"
            placeholder="请输入货品名称"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="需求日期" prop="demandDate">
        <el-date-picker clearable
                        v-model="queryParams.demandDate"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择需求日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="执行状态" prop="planStatus">
        <el-select v-model="queryParams.planStatus">
          <el-option
              v-for="item in plan_execution_status"
              :key="item.value"
              :label="item.value"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
        >新增采购计划</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="info"
            plain
            icon="Guide"
            @click="handleHistoryPlan"
        >历史计划</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="purchasePlanList" @selection-change="handleSelectionChange"
              style="margin-top: 15px; height: 80%">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="采购计划编号" fixed align="center" prop="planNo" width="140" />
      <el-table-column label="货品编码" align="center" prop="code" width="120"/>
      <el-table-column label="货品名称" align="center" prop="rawProductName" width="100"/>
      <el-table-column label="货品数量(吨)" align="center" prop="quantity" width="100" />
      <el-table-column label="预算(元)" align="center" prop="budget" width="100" />
      <el-table-column label="采购价格(元)" align="center" prop="unitPrice" width="100" />
      <el-table-column label="需求日期" align="center" prop="demandDate" width="100">
        <template #default="scope">
          <span>{{ parseTime(scope.row.demandDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预期交货时间" align="center" prop="expectedDeliveryTime" width="110">
        <template #default="scope">
          <span>{{ parseTime(scope.row.expectedDeliveryTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划状态" align="center" prop="planStatus" >
        <template #default="scope">
          <el-tag :type="scope.row.planStatus === '已执行' ? 'success' : 'primary'" disable-transitions>
            {{ scope.row.planStatus}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="修改日期" align="center" prop="modifiedDate" width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.modifiedDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" header-align="center" align="left" prop="remarks" width="180px"/>
      <el-table-column label="操作" fixed="right" align="center" class-name="small-padding fixed-width" width="150">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" >修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改采购计划对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body @close="selectCodeChange = false;">
      <el-form ref="purchaseplanRef" :model="form" :rules="rules" label-width="100px" label-position="top">
        <el-row gutter="15">
          <el-col :span="12">
            <el-form-item label="货品编码" prop="code">
              <el-select v-model="form.code" placeholder="请选择货品编码"
                         style="width: 100%" @change="handleCodeSelectChange"
                         :disabled="selectCodeChange">
                <el-option
                    v-for="item in productList"
                    :key="item.code"
                    :label="formatterCode(item)"
                    :value="item.code"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="货品数量" prop="quantity">
              <el-input v-model="form.quantity" placeholder="请输入货品数量" />
            </el-form-item>
            <el-form-item label="预算" prop="budget">
              <el-input v-model="form.budget" placeholder="请输入预算" />
            </el-form-item>
            <el-form-item label="预期交货日期" prop="expectedDeliveryTime">
              <el-date-picker clearable
                              v-model="form.expectedDeliveryTime"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择预期交货时间"
                              style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="货品名称" prop="rawProductName">
              <el-input v-model="form.rawProductName" placeholder="请输入货品名称" disabled/>
            </el-form-item>
            <el-form-item label="货品数量单位" prop="quantityUnit">
              <el-input v-model="form.quantityUnit" placeholder="请输入货品数量单位" disabled/>
            </el-form-item>
            <el-form-item label="预算单位" prop="currencyUnit">
              <el-input v-model="form.currencyUnit" placeholder="请输入预算单位" disabled/>
            </el-form-item>
            <el-form-item label="采购价格" prop="unitPrice">
              <el-input v-model="form.unitPrice" placeholder="请输入采购价格">
                <template #suffix>
                  <span>元</span>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="ForecastShow">
import {
  getPurchasePlan,
  delPurchasePlan,
  addPurchasePlan,
  updatePurchasePlan,
  listLatestPurchasePlan,
  getLatestPlanNo
} from "@/api/purchase/purchasePlan.js";
import { parseTime } from "@/utils/ruoyi.js";
import {onMounted} from "vue";
import {listDictDataAll} from "@/api/purchase/DictData.js";

const { proxy } = getCurrentInstance();

const purchasePlanList = ref([]);
const productList = ref([]);
const selectCodeChange = ref(false);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const { plan_execution_status } = proxy.useDict("plan_execution_status");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    rawProductName: null,
    demandDate: null,
    planStatus: null,
  },
  rules: {
    supplierCode: [
      { required: true, message: "供应商编码不能为空", trigger: "blur" }
    ],
    code: [
      { required: true, message: "货品编码不能为空", trigger: "blur" }
    ],
    rawProductName: [
      { required: true, message: "货品名称不能为空", trigger: "blur" }
    ],
    quantity: [
      { required: true, message: "货品件数不能为空", trigger: "blur" }
    ],
    budget: [
      { required: true, message: "预算不能为空", trigger: "blur" }
    ],
    demandDate: [
      { required: true, message: "需求日期不能为空", trigger: "blur" }
    ],
    planStatus: [
      { required: true, message: "计划状态不能为空", trigger: "change" }
    ],
  }
});

const weightUnits = ref([
  {
    label:"吨",
    value:"吨"
  },
  {
    label:"千克",
    value:"千克"
  },
  {
    label:"克",
    value:"克"
  },
])

const currencyUnits = ref([
  {
    label:"元",
    value:"元"
  },
  {
    label:"万元",
    value:"万元"
  },
])

const { queryParams, form, rules } = toRefs(data);

/** 挂载时调用 */
onMounted(() => {
  getList();
});

/** 查询采购计划列表 */
function getList() {
  loading.value = true;
  listLatestPurchasePlan(queryParams.value).then(response => {
    purchasePlanList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });

  //初始化货品列表 ->新增采购计划
  const query = {type: '货品'}
  listDictDataAll(query).then(response => {
    productList.value = response.data;
  })
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    planNo: null,
    supplierCode: null,
    rawProductBatch: null,
    rawProductName: null,
    quantity: null,
    quantityUnit: '吨',
    budget: null,
    currencyType: null,
    currencyUnit: '元',
    demandDate: null,
    expectedDeliveryTime: null,
    createdTime: null,
    modifiedDate: null,
    modifiedBy: null,
    planStatus: null,
    remarks: null
  };
  proxy.resetForm("purchaseplanRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.planNo);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加采购计划";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _planNo = row.planNo || ids.value
  if(row.planStatus === "已执行"){
    proxy.$modal.msgError("已执行计划无法修改");
    return;
  }
  getPurchasePlan(_planNo).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改采购计划";
    selectCodeChange.value = true;
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["purchaseplanRef"].validate(valid => {
    if (valid) {
      if (form.value.planNo != null) {
        updatePurchasePlan(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        form.value.demandDate = form.value.expectedDeliveryTime;
        getLatestPlanNo().then(response => {
          form.value.planNo = handlePlanNoFormat(response.data);
          form.value.cycleNo = response.data.slice(0,-3);
          addPurchasePlan(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          });
        })
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _planNos = row.planNo || ids.value;
  proxy.$modal.confirm('是否确认删除采购计划编号为"' + _planNos + '"的数据项？').then(function() {
    return delPurchasePlan(_planNos);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('purchasePlan/export', {
    ...queryParams.value
  }, `purchasePlan_${new Date().getTime()}.xlsx`)
}

/** 采购计划编号转化 */
function handlePlanNoFormat(planNo) {
  let numPart = planNo.slice(-3);
  let incrementedNum = (parseInt(numPart, 10) + 1).toString();
  incrementedNum = incrementedNum.padStart(3, '0');
  return  planNo.slice(0, -3) + incrementedNum;
}

function handleHistoryPlan(){
  proxy.$router.push({
    path: '/HistoryPlan'
  });
}

/** 格式化选择列表的货品编码 */
function formatterCode(item){
  return item.code + ' - ' + item.name;
}

/** 新增采购计划选择的货品编码改变时调用 */
function handleCodeSelectChange(value){
  productList.value.forEach(item => {
    if(item.code === value){
      form.value.rawProductName = item.name;
    }
  })
}

</script>

<style scoped>
.custom-large-button {
  font-size: 17px; /* 调整字体大小 */
  padding: 15px 30px; /* 增加内边距 */
  height: 40px; /* 设置高度 */
  width: 120px; /* 设置宽度 */
}
</style>